import React, { useEffect, useState, useCallback } from 'react'
import './Banner.scss'
import Image from '../Image'
import axios from '../../axios'

export default function Banner() {
  const [currentBannerIndex, setCurrentBannerIndex] = useState(0)
  const bannerH = 350
  const bannerW = 700
  const interval = 3000
  const [bannerList, setBannerList] = useState([])
  const pre = () => {
    setCurrentBannerIndex(subtract())
  }
  const next = () => {
    setCurrentBannerIndex(increase())
  }
  
  const clickDot = (index) => {
    setCurrentBannerIndex(index)
  }

  const increase = useCallback(() => {
    return currentBannerIndex >= bannerList.length - 1 ? 0 : currentBannerIndex + 1
  },[currentBannerIndex, bannerList])
  const subtract = () => {
    return currentBannerIndex <= 0 ? bannerList.length - 1 : currentBannerIndex - 1
  }

  useEffect(() => {
    let timer = setInterval(() => {
      setCurrentBannerIndex(increase())
    }, interval)
    return () => {
      clearInterval(timer)
    }
  }, [increase])

  useEffect(() => {
    axios.get('/banner').then(res => {
      setBannerList(res.data)
    })
  }, [])

  return (
    <div className='global-banner' style={{height: bannerH + 'px', width: bannerW+ 'px'}}>
      {
        bannerList.map((item, index) => {
          return (
            <div className='banner-item' key={index} style={{left: ((index - currentBannerIndex) * bannerW) + 'px', transition: '.5s'}}>
              <Image className='img' src={item.imageUrl}></Image>
            </div>
          )
        })
      }
      <div className='next-box'>
        <div className='pre' onClick={pre}>{'<'}</div>
        <div className='next' onClick={next}>{'>'}</div>
      </div>
      <div className='dot-box'>
        {
          bannerList.map((_, index) => {
            return <span className={index === currentBannerIndex ? 'dot active' : 'dot'} onClick={() => clickDot(index)} key={index}></span>
          })
        }
      </div>
    </div>
  )
}
